package com.schillerchina.baselibrary.network.interceptor;

import android.os.Build;
import android.util.DisplayMetrics;


import com.google.gson.Gson;
import com.schillerchina.baselibrary.network.App;
import com.schillerchina.baselibrary.network.RetrofitHandler;
import com.schillerchina.baselibrary.network.config.NetConfig;
import com.schillerchina.baselibrary.network.config.TokenBean;
import com.schillerchina.baselibrary.utils.DeviceUtils;
import com.schillerchina.baselibrary.utils.LogUtil;
import com.schillerchina.baselibrary.utils.Pref;
import com.schillerchina.baselibrary.utils.StringUtils;
import com.schillerchina.baselibrary.utils.Symbols;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
import okio.BufferedSource;

/**
 * @author zhangzhiguo
 * @date 2019-08-05 09:39
 * @Description: 网络请求 log 拦截器
 */
public class LogInterceptor implements Interceptor {

    private static final Charset UTF8 = Charset.forName("UTF-8");
    // 是否需要打印接口返回数据
//    private boolean showResponse = BuildConfig.DEBUG;
    private boolean showResponse =true;

    @Override
    public Response intercept(Chain chain) throws IOException {
        try {
            DisplayMetrics metrics = App.getContext().getResources().getDisplayMetrics();
            String width = String.valueOf(metrics.widthPixels);
            String height = String.valueOf(metrics.heightPixels);
            Request.Builder builder = chain.request()
                    .newBuilder()
                    .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                    .addHeader("Accept-Encoding", "gzip, deflate")
                    .addHeader("Connection", "keep-alive")
                    .addHeader("Accept", "*/*")
                    .addHeader("X-Request-Id", String.valueOf(System.currentTimeMillis()))
                    .addHeader("requestId", String.valueOf(System.currentTimeMillis()))
                    //新的接口是不需要header Authorization的。
//                    .addHeader("Authorization", AuthManager.getAuthorization())
//                    .addHeader("userId", userId)
//                    .addHeader("userUuid", userUuid)
                    .addHeader("mac", DeviceUtils.getAndroidID())
                    .addHeader("model", Build.BRAND + "-" + Build.PRODUCT)
                    .addHeader("os", Build.VERSION.RELEASE)
                    .addHeader("screen", width + "*" + height)
                    .addHeader("clientId", String.valueOf(2));

            Map<String, String> configHeader = NetConfig.getHeaders();
            if (configHeader != null) {
                for (String k : configHeader.keySet()) {
                    builder.addHeader(k, configHeader.get(k));
                }
            }
            Request request = builder.build();

            long t1 = System.currentTimeMillis();
            Response response = chain.proceed(request);
            long t2 = System.currentTimeMillis();
            long time = t2 - t1;

            StringBuilder stringBuilder = new StringBuilder();
            BufferedSource source = response.body().source();
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();
            String resBody = FormattingJson(buffer.clone().readString(UTF8));
            if (showResponse) {
                String type = request.method();
                stringBuilder.append("\n--------------------begin--------------------")
                        .append("\nmethod--> ").append(type)
                        .append("\nnetwork code--> ").append(response.code() + "")
                        .append("\nURL--> ").append(request.url() + "")
                        .append("\ntime--> ").append(time + "")
                        .append("\nrequest headers--> ").append(request.headers() + "")
                        .append("\nrequest--> ").append(bodyToString(request.body()))
                        .append("\nresponse--> ").append(resBody);
            } else {
                stringBuilder.append("\nURL--> ").append(request.url() + "")
                        .append("\ntime--> ").append(time + "");
            }
            if (showResponse) {
                LogUtil.longLog("net:", stringBuilder.toString());
            }
//            if (Pref.getString("access_token","").length()>0) {
//                String token = refreshToken(Pref.getString("access_token",""));
//                if (!StringUtils.isEmpty(token)) {
//                    NetConfig.getHeaders().put("Authorization", token);
//            NetConfig.getHeaders().put("Authorization",Pref.getString("token_type","")+" "+Pref.getString("access_token",""));
//                    Request newRequest = chain.request()
//                            .newBuilder()
//                            .header("Authorization", token)
//                            .build();
//                    return chain.proceed(newRequest);
//                }
//            }

            return response;
        } catch (Exception e) {
            throw e;
        }
    }

    private static String refreshToken(String to) {

        try {
            if (StringUtils.isEmpty(to)) {
                return "";
            }
            retrofit2.Response<TokenBean> response =
                    RetrofitHandler.getRetrofit().create(TokenApi.class)
                            .getNewToken().execute();
            TokenBean tokenBean = response.body();
            String token = tokenBean.getAccess_token();
            Pref.put("access_token", token);
            return tokenBean.getToken_type() + " " + token;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 创建时间：2017/12/27 10:05
     * <p>
     * 描述：请求数据转 string 并格式化打印
     *
     * @author zpw
     */
    private static String bodyToString(final RequestBody request) {

        try {
            final Buffer buffer = new Buffer();

            if (request != null) {

                request.writeTo(buffer);
                // 获得 string
                String str = buffer.readUtf8();
                str = str.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                // URL 解码
                String decodeStr = URLDecoder.decode(str, "UTF-8");
                String[] splitStr = decodeStr.split("&");

                List<String> list = new ArrayList<>();
                for (int i = 0; i < splitStr.length; i++) {
                    list.add(splitStr[i]);
                }
                Gson gson = new Gson();
                String result = gson.toJson(list);
                return result;
            } else {
                return "request not work";
            }

        } catch (final IOException e) {
            return "did not work";
        }
    }


    /**
     * 创建时间：2017/11/6 11:32  描述：格式化 json 数据
     */
    private static String FormattingJson(String json) {
        if (json == null || json.length() == 0) {
            return "Empty/Null json content";
        }
        try {
            json = json.trim();
            if (json.startsWith(Symbols.BRACE_LEFT)) {
                JSONObject jsonObject = new JSONObject(json);
                return jsonObject.toString(2);
            }
            if (json.startsWith(Symbols.BRACKET_LEFT)) {
                JSONArray jsonArray = new JSONArray(json);
                return jsonArray.toString(2);
            }
            return "Invalid Json" + Symbols.ENTER + json;
        } catch (JSONException e) {
            return "Invalid Json" + Symbols.ENTER + json;
        } catch (OutOfMemoryError e) {
            return "OutOfMemoryError";
        }
    }

    public void setShowResponse(boolean showResponse) {
        this.showResponse = showResponse;
    }
}
